package com.kzd.btgame.app

import android.content.Context
import android.content.pm.PackageManager
import androidx.multidex.MultiDex
import androidx.room.Room
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.kzd.btgame.BuildConfig
import com.kzd.btgame.R
import com.kzd.btgame.app.SPSConstance.channel
import com.kzd.btgame.app.SPSConstance.forceLogin
import com.kzd.btgame.db.AppDatabase
import com.kzd.btgame.manage.DownloadManager
import com.kzd.btgame.utils.ApkFile
import com.module.lemlin.http.HttpServiceFactory
import com.module.lemlin.app.OwnerApplication
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import org.json.JSONObject
import rxhttp.RxHttpPlugins

class GTApplication : OwnerApplication() {

    companion object {

        const val DB_NAME = "GTGame.db"
        lateinit var appDatabase: AppDatabase

        init {
            //设置全局的Header构建器
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
                MaterialHeader(context).setColorSchemeResources(R.color.colorMain)
            }
            //设置全局的Footer构建器
            SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
                ClassicsFooter(context)//.setSpinnerStyle(SpinnerStyle.Translate).setAccentColorId(R.color.colorPrimary)
            }
        }

    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        //初始dex
        MultiDex.install(base)
    }

    override fun onCreate() {
        super.onCreate()

        if (SPSConstance.isReadAgree == true) {
            initSDK()
        }

        LogUtils.e("==============APP_APPLICATION_ID:${BuildConfig.APP_APPLICATION_ID}")
    }

    fun initSDK(): Boolean {

        initReadMeatInfo()

        //初始数据库
        appDatabase = Room.databaseBuilder(
            application, AppDatabase::class.java, DB_NAME
        ).fallbackToDestructiveMigration()
            .allowMainThreadQueries()
            .build()

        //设置友盟log开关
        UMConfigure.setLogEnabled(true)
        //初始化友盟SDK
        UMConfigure.init(this, null, channel, UMConfigure.DEVICE_TYPE_PHONE, null)
        // 微信设置
        PlatformConfig.setWeixin("wxf901b5b8439da3f8", "84a7555beb12ef494cdbc9f9aea13238")
        PlatformConfig.setWXFileProvider("com.kzd.btgame.fileProvider")
        // QQ设置
        PlatformConfig.setQQZone("101961687", "c82893c735c5bea095790ff03a8ff16d")
        PlatformConfig.setQQFileProvider("com.kzd.btgame.fileProvider")

        //初始化RxHttp
        RxHttpPlugins.init(HttpServiceFactory.client().build())
            .setOnParamAssembly {
                it.addHeader("version", AppUtils.getAppVersionName())
                it.addHeader("channel", channel)
                it.addHeader("ua", System.getProperty("http.agent")?.run {
                    substring(indexOf("("), indexOf(")") + 1)
                })
                it.add("uid", SPSConstance.uid)
                it.add("member_id", SPSConstance.memberId)
            }
            .setDebug(true)

        DownloadManager.instance.initData()

        return true
    }

    private fun initReadMeatInfo() {
        val meatInfo = ApkFile.readMETAINFO(this, "META-INF/gtgame.channel.properties")
        if (meatInfo.isNullOrEmpty()) {
            val appInfo = packageManager.getApplicationInfo(
                packageName, PackageManager.GET_META_DATA
            )
            channel = appInfo.metaData
                .getString("UMENG_CHANNEL", "DEFAULT")
            forceLogin = appInfo.metaData
                .getBoolean("FORCE_LOGIN", false)
        } else {
            channel = try {
                JSONObject(meatInfo).getString("UMENG_CHANNEL")
            } catch (e: Exception) {
                "DEFAULT"
            }
            forceLogin = try {
                JSONObject(meatInfo).getBoolean("FORCE_LOGIN")
            } catch (e: Exception) {
                false
            }
        }
    }

}